<?php
include 'autoload.php';

$id = $_GET['id'];
$library = new weebUILibrary( $_GET['library'] );
if ( $id )
{
    $data = sqlite_fetch_array( $library->query( "SELECT item_image, item_location FROM items WHERE item_id='$id'" ) );
    $filename = $data['item_image'];
    // # If the image is inside mp3, try to find image in folder!
    if ( substr( $filename, 0, 5 ) == "apic:" )
    {
        $dir = dirname( $data['item_location'] );
        $h = opendir( $dir );
        while ( $file = readdir( $h ) )
        {
            if ( ( $file != "." ) && ( $file != ".." ) )
            {
                $ext = strtolower( strrchr( $file, "." ) );
                if ( ( $ext == ".jpg" ) || ( $ext == ".jpeg" ) || ( $ext == ".gif" ) || ( $ext == ".png" ) || ( $ext == ".bmp" ) ) $filename = "$dir\\$file";
            }
        }
    }

    if ( !$filename ) $filename = "images/noimage.jpg";
    if ( ( $_GET['w'] ) && ( $_GET['h'] ) )
    {
        $newwidth = $_GET['w'];
        $newheight = $_GET['h'];
    }
    else
    {
        $newwidth = $library->thumb_width;
        $newheight = $library->thumb_height;
    }
    list( $width, $height ) = getimagesize( $filename );
    $thumb = imagecreatetruecolor( $newwidth, $newheight );

    if ( exif_imagetype( $filename ) == 1 )
    {
        $source = imagecreatefromgif( $filename );
        header( 'Content-type: image/jpeg' );
    }
    if ( exif_imagetype( $filename ) == 2 )
    {
        $source = imagecreatefromjpeg( $filename );
        header( 'Content-type: image/gif' );
    }
    if ( exif_imagetype( $filename ) == 3 )
    {
        $source = imagecreatefrompng( $filename );
        header( 'Content-type: image/png' );
    }
    if ( exif_imagetype( $filename ) == 6 )
    {
        $source = imagecreatefromwbmp( $filename );
        header( 'Content-type: image/bmp' );
    }

    imagecopyresized( $thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
    imagejpeg( $thumb );
}

else
{
    throw new weebUIMissingDataException( '$_GET[id]' );
}

?>